﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using Reactor.Environment;
using Reactor.Messaging;

namespace Reactor.Workflow.Activities
{
    public class SendMessage<T> : CodeActivity where T : class 
    {
        [RequiredArgument]
        public InArgument<T> MessageToSend { get; set; }

        public InArgument<IEnumerable<IMessagingChannel>> Destinations { get; set; }

        public InArgument<bool> CorrelateWithCurrentWorkflowInstance { get; set; }

        #region Overrides of CodeActivity

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override void Execute(CodeActivityContext context)
        {
            if(Context.ServiceBus == null)
                throw new InvalidOperationException("No ServiceBus instance found at Reactor.Environment.Context.ServiceBus.");

            var message = context.GetValue(MessageToSend);
            var destinations = context.GetValue(Destinations);
            var correlate = context.GetValue(CorrelateWithCurrentWorkflowInstance);
            if (destinations != null && destinations.Any())
            {
                foreach (var destination in destinations)
                {
                    if(correlate)
                        Context.ServiceBus.Send(message, destination, context.WorkflowInstanceId);
                    else
                        Context.ServiceBus.Send(message, destination);
                }
            }
            else
            {
                if (correlate)
                    Context.ServiceBus.Send(message, context.WorkflowInstanceId);
                else
                    Context.ServiceBus.Send(message);
            }
        }

        #endregion
    }
}
